/* File Name: client.c */

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include <time.h>

#define MAXLINE 4096

int main(int argc, char** argv)
{
    int    sockfd, n,rec_len;
    char    recvline[4096], sendline[4096];
    char    buf[MAXLINE];
    struct sockaddr_in servaddr;
    int iPort = 8000;
    int iRet = 0;


    if( argc != 3){
        printf("usage: ./client <ipaddress> <port>\n");
        exit(0);
    }

    iPort = atoi(argv[2]);

    while (1)
    {
        if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
            printf("create socket error: %s(errno: %d)\n", strerror(errno),errno);
            exit(0);
        }


        memset(&servaddr, 0, sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(iPort);
        if( inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0){
            printf("inet_pton error for %s\n",argv[1]);
            exit(0);
        }

        time_t ttBefore = time(NULL);
        iRet = connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
        time_t ttAfter = time(NULL);
        printf("connect used time %ds\n", ttAfter-ttBefore);
        if(iRet < 0){
            printf("connect error: %s(errno: %d)\n",strerror(errno),errno);
            close(sockfd);
            sleep(1);
            continue;
        }
        snprintf(sendline, sizeof(sendline), "test hello socket %d",  sockfd);
        if( send(sockfd, sendline, strlen(sendline), 0) < 0)
        {
            printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);
        }
        close(sockfd);
        sleep(1);
    }


    printf("send msg to server: \n");
    fgets(sendline, 4096, stdin);
    if( send(sockfd, sendline, strlen(sendline), 0) < 0)
    {
        printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);
        exit(0);
    }
    if((rec_len = recv(sockfd, buf, MAXLINE,0)) == -1) {
        perror("recv error");
        exit(1);
    }
    buf[rec_len]  = '\0';
    printf("Received : %s ",buf);
    close(sockfd);
    exit(0);
}